package cn.harperDog.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author hua
 * @description
 * @date 2022/3/3
 *
 * 根据传入的类名，方法名，参数值构造一个接口的对象
 * 方法名匹配则输出参数值，方法名不匹配则输出null
 */
public class MatchMethod {
    public static void main(String[] arges) throws Exception{
        IA ia = (IA) createObject(IA.class.getName()+"$getHelloName=Abc");
        System.out.println(ia.getHelloName()); //方法名匹配的时候，输出“Abc”
        ia = (IA) createObject(IA.class.getName()+"$getTest=Bcd");
        System.out.println(ia.getHelloName()); //方法名不匹配的时候，输出null
    }

    //请实现方法createObject，接口中"getName()"方法名仅仅是个示例，不能写死判断

    public static Object createObject(String str) throws Exception {
        String[] classMethodNameAndParaArray = str.split("\\$");
        String className = classMethodNameAndParaArray[0];
        String methodNameAndPara = classMethodNameAndParaArray[1];
        String[] splitArray = methodNameAndPara.split("=");
        String name = splitArray[0];
        String value = splitArray[1];
        Class<?> classObj = Class.forName(className);

        return Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{classObj}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(method.getName().equals(name)){
                    return value;
                }
                return null;
            }
        });
    }

    //请实现方法createObject，接口中"getName()"方法名仅仅是个示例，不能写死判断

    public static Object createObject2(String str) throws Exception {

        String[] classMethodNameAndParaArray = str.split("\\$");
        String className = classMethodNameAndParaArray[0];
        String methodNameAndPara = classMethodNameAndParaArray[1];
        String[] splitArray = methodNameAndPara.split("=");
        String name = splitArray[0];
        String value = splitArray[1];
        Class<?> classObj = Class.forName(className);
        MethodInterceptor methodInterceptor = new MethodInterceptor() {

            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                //判断参数里面的方法名是否是调用的方法名
                if(method.getName().equals(name)){
                    return value;
                }
                return null;
            }
        };

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(IA.class);
        enhancer.setCallback(methodInterceptor);
        IA proxy= (IA)  enhancer.create();
        return proxy;

    }
}

interface IA {
    String getHelloName();
}